package com.example.printscreen.printscreen;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.printscreen.printscreen.bean.LoginInfo;
import com.example.printscreen.printscreen.bean.LoginUser;
import com.example.printscreen.printscreen.bean.UploadData;
import com.example.printscreen.printscreen.bean.UploadFile;
import com.example.printscreen.printscreen.network.NetworkRequest;
import com.example.printscreen.printscreen.network.TupaiSubscriber;
import com.example.printscreen.printscreen.utils.BitmapUtil;
import com.example.printscreen.printscreen.utils.Constant;
import com.example.printscreen.printscreen.utils.Utils;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;

import static com.example.printscreen.printscreen.utils.Constant.IMAGE_SAVED_DIR;

public class MainActivity extends RxAppCompatActivity implements Handler.Callback {
    /**
     * 三个保存图片的文件夹
     * 1. 当前处理的原图和作品文件夹，这里是美图的文件夹
     * 2. 所有原图和作品的文件夹
     * 3. 待上传图片的文件夹（包括上传失败的图片）
     */

    //suwei add
    /*
    *    函数名：printScreen
    *    参数  ：rtsp_url：网络流地址，支持RTSP，HLS，RTMP
    *            image_path：图片保存地址
    *    返回值： 1 ： 成功
    *            -1 ： 网络连接失败
    *            -2 ： 文件保存失败
     */
    public native int printScreen(String rtsp_url, String image_path);
    //
    private Button mChangeBtn;
    private Button mBackBtn;
    private Handler mHandler = new Handler(this);

    private Context mContext;
    private UploadManager mUploadManager;
    private ColorDrawable colorDrawable;

    private File mPathDir = new File(IMAGE_SAVED_DIR);                  // 当前处理的目录
    private File mUploadPathDir = new File(Constant.UPLOAD_IMAGE_DIR);  // 上传目录
    private File mAllImageDir = new File(Constant.ALL_IMAGE_DIR);       // 所有图片的目录

    private String fileHandlePath;              // 处理图片的本地路径
    private String fileUploadPath;              // 上传图片的本地路径
    private String fileAllPath;                 // 全部图片的本地路径

    private final int MAX_ALL_IMAGE_DIRECTORY = 5;      // 全部图片路径所能保存的最大图片数
    private final int HANDLE_MSG = 0x23;         // 非按键处理流程的msg
    private int HANDLE_WAIT_TIME = 5000;         // 等待时间

    //suwei add
    static {
        System.loadLibrary("avcodec-56");
        System.loadLibrary("avdevice-56");
        System.loadLibrary("avfilter-5");
        System.loadLibrary("avformat-56");
        System.loadLibrary("avutil-54");
        System.loadLibrary("swresample-1");
        System.loadLibrary("swscale-3");
        System.loadLibrary("FFmpegCodec");
    }
    //

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        mChangeBtn = (Button) findViewById(R.id.change_button);
        mBackBtn = (Button) findViewById(R.id.back);
        Drawable background = mChangeBtn.getBackground();
        colorDrawable = (ColorDrawable) background;

        initUpload();                    // 初始化七牛上传
        GetHandleImagePath();            // 获取图片
        UploadDirImage();                // 循环上传图片
        initListeners();
    }

    private void initListeners() {
        mChangeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (colorDrawable.getColor() == Color.parseColor("#00FF00")) {
                    mChangeBtn.setText("SpecialEffects");
                    mChangeBtn.setBackgroundColor(Color.parseColor("#FFFF00"));

                } else if (colorDrawable.getColor() == Color.parseColor("#FFFF00")) {

                    mChangeBtn.post(new Runnable() {
                        @Override
                        public void run() {
                            mChangeBtn.setText("");
                            mChangeBtn.setBackgroundColor(Color.parseColor("#FF0000"));
                        }
                    });
                    mChangeBtn.invalidate();

                    mHandler.removeMessages(HANDLE_MSG);    // 取消非按键处理流程的获取图片

                    File[] childFile = mPathDir.listFiles();
                    if (childFile.length < 2) {
                        Toast.makeText(MainActivity.this, "存在异常", Toast.LENGTH_SHORT).show();

                        // 异常时，所有图片文件夹需要删除一张图片
                        File[] allPathChildFile = mAllImageDir.listFiles();
                        if (allPathChildFile.length >= MAX_ALL_IMAGE_DIRECTORY) {
                            DeleteFile(allPathChildFile[0]);
                        }

                    } else {
                        Toast.makeText(MainActivity.this, "正常处理", Toast.LENGTH_SHORT).show();
                        // 正常处理时，所有图片文件夹需要删除两张图片
                        File[] allPathChildFile = mAllImageDir.listFiles();
                        if (allPathChildFile.length >= MAX_ALL_IMAGE_DIRECTORY) {
                            DeleteFile(allPathChildFile[0]);
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    File[] allPathChildFile = mAllImageDir.listFiles();
                                    DeleteFile(allPathChildFile[0]);
                                }
                            }, 1000);
                        }
                        File file = childFile[childFile.length - 1];
                        SaveAlterHandleImage(file.getPath());
                    }

                    // 删除当前处理文件夹下的所有图片
                    RecursionDeleteFile(mPathDir);

                    // 循环处理流程
                    GetHandleImagePath();
                }
            }
        });

        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 保存处理后的图片到上传和全部文件夹
     */
    private void SaveAlterHandleImage(String filePath) {
        final Bitmap bmp = BitmapUtil.getDiskBitmap(filePath);

        final String allFileName = "All_" + System.currentTimeMillis() + ".jpg";
        fileAllPath = Constant.ALL_IMAGE_DIR + allFileName;
        BitmapUtil.saveImgToDisk(Constant.ALL_IMAGE_DIR, allFileName, bmp);
        // 刷新文件系统
        updateGallery(fileAllPath);

        SimpleDateFormat sDateFormat = new SimpleDateFormat("hh");
        String hourStr = sDateFormat.format(new java.util.Date());
        int hour = Integer.parseInt(hourStr);
        int startHour = Integer.parseInt(LoginUser.getInstance().getBegTime());
        int endHour = Integer.parseInt(LoginUser.getInstance().getEndTime());
        if ( hour >= startHour && hour <= endHour) {
            final String uploadFileName = "Upload_" + System.currentTimeMillis() + ".jpg";
            fileUploadPath = Constant.UPLOAD_IMAGE_DIR + uploadFileName;
            BitmapUtil.saveImgToDisk(Constant.UPLOAD_IMAGE_DIR, uploadFileName, bmp);
            updateGallery(fileUploadPath);
        }
    }

    /**
     *  获取非按键处理流程下的，轮询周期的状态
     */
    public void GetRoundThenGetImage() {
        NetworkRequest.getInstance().handleStatus(LoginUser.getInstance().getCode(),
                new TupaiSubscriber<LoginInfo>(mContext) {
                    @Override
                    protected void requestSuccess(LoginInfo loginInfo) {
//                        Utils.showToast("获取状态成功");
                        LoginUser.getInstance().initFromResponse(loginInfo);

                        String roundTime = LoginUser.getInstance().getRoundTime();
                        HANDLE_WAIT_TIME = Integer.parseInt(roundTime);

                        mHandler.removeMessages(HANDLE_MSG);
                        Message msg = mHandler.obtainMessage();
                        msg.what = HANDLE_MSG;
                        mHandler.sendMessageDelayed(msg, HANDLE_WAIT_TIME);
                    }

                    @Override
                    protected void requestError(String error) {
                    }
                });
    }

    /**
     * 上传待上传图片文件夹下的所有图片
     * 循环上传所有的图片，上传全部后，10秒后再试一次有没有新图片需要上传
     */
    private void UploadDirImage() {
//        Utils.showToast("上传图片");
        File[] childFile = mUploadPathDir.listFiles();
        if (childFile.length > 0) {
            File file = childFile[0];
            GetUploadToken(file.getAbsolutePath());
        } else {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    UploadDirImage();
                }
            }, 10000);
        }
    }

    /**
     * 获取上传token
     */
    private void GetUploadToken(final String path) {
        NetworkRequest.getInstance().getUploadToken(MainActivity.this,
                new TupaiSubscriber<UploadFile>(mContext) {
                    @Override
                    protected void requestSuccess(UploadFile uploadFile) {
                        if (TextUtils.isEmpty(uploadFile.getToken())) {
                            return;
                        }
                        UploadToQiniu(uploadFile, path);
                    }

                    @Override
                    protected void requestError(String error) {
                        Utils.showToast("上传失败:" + error);
                        UploadDirImage();
                    }
                });

    }

    /**
     * 上传到七牛
     */
    private void UploadToQiniu(final UploadFile uploadFile, String path) {
        mUploadManager.put(path, uploadFile.getKey(), uploadFile.getToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        // 上传图片
                        NetworkRequest.getInstance().uploadImage(LoginUser.getInstance().getCode(), uploadFile.getUrl(),
                                new TupaiSubscriber<UploadData>(mContext) {

                                    @Override
                                    protected void requestSuccess(UploadData uploadData) {
                                        Utils.showToast("上传成功" );
                                        File[] childFile = mUploadPathDir.listFiles();
                                        DeleteFile(childFile[0]);

                                        UploadDirImage();
                                    }

                                    @Override
                                    protected void requestError(String error) {
                                        Utils.showToast("上传失败:" + error);
                                        UploadDirImage();
                                    }
                                });
                    }
                }, null);
    }

    /**
     * 递归删除文件夹下的所有文件
     */
    public void RecursionDeleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            updateGallery(file.getAbsolutePath());
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            for (File f : childFile) {
                RecursionDeleteFile(f);
            }
        }
    }

    /**
     * 删除一个文件
     */
    public void DeleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            updateGallery(file.getAbsolutePath());
        }
    }

    /**
     * 通知媒体库更新文件  filename是我们的文件全名，包括后缀哦
     */
    private void updateGallery(String filename) {
        MediaScannerConnection.scanFile(this,
                new String[]{filename}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });
    }

    /**
     * 获取要处理的图片地址
     */
    private void GetHandleImagePath() {
        GetRoundThenGetImage();

        String fileName = System.currentTimeMillis() + ".jpg";
        fileHandlePath = IMAGE_SAVED_DIR + fileName;
        int x = printScreen(LoginUser.getInstance().getUrl(), fileHandlePath);
        if (x == 1) {
            Utils.showToast("获取按键流程图片成功");
            mChangeBtn.post(new Runnable() {
                @Override
                public void run() {
                    mChangeBtn.setText("SpecialEffects");
                    mChangeBtn.setBackgroundColor(Color.parseColor("#00FF00"));
                }
            });
            mChangeBtn.invalidate();

            // 下载图片后，通知刷新文件系统
            updateGallery(fileHandlePath);

            // 保存图片到上传和全部文件夹
            Bitmap bmp = BitmapUtil.getDiskBitmap(fileHandlePath);

            final String allFileName = "All_" + System.currentTimeMillis() + ".jpg";
            fileAllPath = Constant.ALL_IMAGE_DIR + allFileName;
            BitmapUtil.saveImgToDisk(Constant.ALL_IMAGE_DIR, allFileName, bmp);
            // 刷新文件系统
            updateGallery(fileAllPath);

            SimpleDateFormat sDateFormat = new SimpleDateFormat("hh");
            String hourStr = sDateFormat.format(new java.util.Date());
            int hour = Integer.parseInt(hourStr);
            int startHour = Integer.parseInt(LoginUser.getInstance().getBegTime());
            int endHour = Integer.parseInt(LoginUser.getInstance().getEndTime());
            if ( hour >= startHour && hour <= endHour) {
                final String uploadFileName = "Upload_" + System.currentTimeMillis() + ".jpg";
                fileUploadPath = Constant.UPLOAD_IMAGE_DIR + uploadFileName;
                BitmapUtil.saveImgToDisk(Constant.UPLOAD_IMAGE_DIR, uploadFileName, bmp);
                updateGallery(fileUploadPath);
            }
        } else {
            Utils.showToast("获取图片失败");
            GetHandleImagePath();
        }
    }

    /**
     *  获取不用按键精灵处理的图片
     */
    private void GetCommonImagePath() {

        final String allFileName = "All_" + System.currentTimeMillis() + ".jpg";
        fileAllPath = Constant.ALL_IMAGE_DIR + allFileName;
        int x = printScreen(LoginUser.getInstance().getUrl(), fileAllPath);
        if (x == 1) {
            Utils.showToast("获取非按键流程图片成功");

            // 下载图片后，通知刷新文件系统
            updateGallery(fileAllPath);

            // 保存图片到上传和全部文件夹
            Bitmap bmp = BitmapUtil.getDiskBitmap(fileAllPath);

            SimpleDateFormat sDateFormat = new SimpleDateFormat("hh");
            String hourStr = sDateFormat.format(new java.util.Date());
            int hour = Integer.parseInt(hourStr);
            int startHour = Integer.parseInt(LoginUser.getInstance().getBegTime());
            int endHour = Integer.parseInt(LoginUser.getInstance().getEndTime());
            if ( hour >= startHour && hour <= endHour) {
                final String uploadFileName = "Upload_" + System.currentTimeMillis() + ".jpg";
                fileUploadPath = Constant.UPLOAD_IMAGE_DIR + uploadFileName;
                BitmapUtil.saveImgToDisk(Constant.UPLOAD_IMAGE_DIR, uploadFileName, bmp);
                updateGallery(fileUploadPath);
            }
        }
    }

    /**
     * 初始化上传
     */
    private void initUpload() {
        Configuration config = new Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                .connectTimeout(10) // 链接超时。默认10秒
                .responseTimeout(60) // 服务器响应超时。默认60秒
                .recorder(null)  // recorder分片上传时，已上传片记录器。默认null
                .recorder(null, null)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Zone.httpsAutoZone) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();

        mUploadManager = new UploadManager(config);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case HANDLE_MSG:
                GetCommonImagePath();
                GetRoundThenGetImage();
                break;
        }
        return false;
    }
}
